package com.simple.mybaits.simplemybatis.session;

import com.simple.mybaits.simplemybatis.Configuration;
import com.simple.mybaits.simplemybatis.ds.DataSourceFacotry;
import com.simple.mybaits.simplemybatis.ds.impl.JdbcDataSourceFactory;
import com.simple.mybaits.simplemybatis.session.impl.DefalutSqlSession;

import javax.sql.DataSource;

/**
 * @author :  zxj
 * @package :  com.simple.mybaits.simplemybatis.session
 * @date :  2018/5/21
 * @description : sqlsession的factory
 */
public class SqlsessionFactory {

    private DataSource dataSource;
    private Configuration configuration;

    /**
     * 创建者
     */
    public SqlSession build() {
        this.configuration = new Configuration();
        DataSourceFacotry dataSourceFacotry = new JdbcDataSourceFactory();
        dataSourceFacotry.setProperties(configuration.load());
        this.dataSource = dataSourceFacotry.getDataSource();
        //扫描接口包
        configuration.doScanMapper(configuration.getKey(Configuration.MAPPER_SCAN_BASEPACKAGE));

        //注册mapperStatement
        configuration.registerMapperStatement();

        return new DefalutSqlSession(configuration, dataSource);
    }


    /**
     * 创建代理
     *
     * @param type
     * @param <T>
     * @return
     */
    public <T> T getMapper(Class<?> type) {
        return (T) configuration.getMapperProxyRegister().get(type);
    }


}
